import { defineStore } from 'pinia';
import request from '../utils/request';
import { ref } from 'vue';

export const useProductOrderStore = defineStore('productOrder', {
  state: () => ({
    orders: [],
    total: 0,
    loading: false,
    orderDetail: null
  }),
  actions: {
    // 获取订单列表，支持条件查询
    async fetchOrders(params = {}) {
      this.loading = true;
      try {
        const response = await request.get('/employee-pet/product/order/list', { params });
        if (response && response.code === 200) {
          if (Array.isArray(response.data)) {
            this.orders = response.data;
            this.total = response.data.length;
          } else if (Array.isArray(response.data?.data)) {
            this.orders = response.data.data;
            this.total = response.data.total || 0;
          } else {
            this.orders = [];
            this.total = 0;
          }
        } else {
          this.orders = [];
          this.total = 0;
        }
        return response;
      } catch (error) {
        this.orders = [];
        this.total = 0;
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 新增订单
    async addOrder(order) {
      try {
        const response = await request.post('/employee-pet/product/order/add', order);
        if (response && (response.code === 200 || response.success)) {
          await this.fetchOrders();
        }
        return response;
      } catch (error) {
        throw error;
      }
    },

    // 修改订单
    async updateOrder(order) {
      try {
        const response = await request.post('/employee-pet/product/order/update', order);
        if (response && (response.code === 200 || response.success)) {
          await this.fetchOrders();
        }
        return response;
      } catch (error) {
        throw error;
      }
    },

    // 删除订单
    async deleteOrder(id) {
      try {
        const response = await request.post(`/employee-pet/product/order/delete/${id}`);
        if (response && (response.code === 200 || response.success)) {
          await this.fetchOrders();
        }
        return response;
      } catch (error) {
        throw error;
      }
    },

    // 获取订单详情
    async fetchOrderDetail(id) {
      try {
        const response = await request.get(`/employee-pet/product/order/detail/${id}`);
        if (response && response.code === 200) {
          this.orderDetail = response.data;
        } else {
          this.orderDetail = null;
        }
        return response;
      } catch (error) {
        this.orderDetail = null;
        throw error;
      }
    },

    // 设置订单列表（本地状态管理）
    setOrders(list) {
      this.orders = list;
    }
  }
}); 